using System;
using System.Collections.Generic;
using System.Linq;
using Karma.Framework.Core.Domain;
using Karma.Framework.Core.Metadata.Description;
using Karma.Framework.Core.Metadata.Mapping;
using Karma.Framework.Core.Modules.Metadata.Converter;
using Karma.Framework.Core.Repository;
using Karma.Framework.Core.Repository.Configuration;
using Karma.Framework.Core.Serialization;
using Karma.Framework.Core.Services;
using Karma.Framework.Core.Utils;

namespace Karma.Framework.Core.Modules.Metadata.Designer
{
    public class DesignerService: IDesignerService
    {
        private static IDictionary<string, EntityDescription> _entityDescriptions = new Dictionary<string, EntityDescription>();

        public DesignerService(IEntityRepository repo)
        {
            Repository = repo;
        }

        private IEntityRepository Repository { get; set; }

        public IList<string> GetEntities()
        {
            return (from e in RepositoryConfiguration.Entities
                    orderby e.Name
                    select e.Name).ToList();
        }

        [SerializationConverters(
           new[] { typeof(EntityDescriptionConverter) })]
        public EntityDescription GetDescription(string typeName)
        {
            var entity = (from e in RepositoryConfiguration.Entities
                          where e.Name == typeName
                          select e).First();

            
            return entity.GetDescription();
        }

        public Entity GetMetadata(string typeName)
        {
            var entity = Repository.Get(typeName);
            if (entity == null)
            {
                entity = new Entity
                             {
                                 Name = typeName
                             };
            }
            return entity;
        }

    }
}
